/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐搜索项组件 - 显示搜索结果中的单个音乐项
 * 迁移自原始项目的 MusicSearchItemWidget，适配新的 MVVM 架构
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../models/music_item_model.dart';
import '../../viewmodels/music_player_view_model.dart';
import '../../viewmodels/music_search_view_model.dart';

/// 音乐搜索项组件
/// 显示搜索结果中的单个音乐项，支持高亮文本和播放状态指示
class MusicSearchItemWidget extends StatelessWidget {
  const MusicSearchItemWidget({
    super.key,
    required this.musicItem,
    required this.query,
    this.onTap,
    this.onMoreTap,
    this.isSelected = false,
  });

  /// 音乐项数据
  final MusicItemModel musicItem;

  /// 搜索关键词，用于高亮显示
  final String query;

  /// 点击回调
  final VoidCallback? onTap;

  /// 更多按钮点击回调
  final VoidCallback? onMoreTap;

  /// 是否被选中
  final bool isSelected;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(
        bottom: 20,
        left: 15,
        right: 15,
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildTitleWidget(context),
                    const SizedBox(height: 4),
                    _buildSubtitleWidget(context),
                  ],
                ),
              ),
              const SizedBox(width: 10),
              _buildMoreButton(context),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建标题组件
  /// 支持高亮显示搜索关键词，当前播放项显示为绿色
  Widget _buildTitleWidget(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, playerViewModel, child) {
        // 检查是否为当前播放项
        final isCurrentPlaying =
            playerViewModel.currentTrack?.id == musicItem.id;

        // 构建高亮文本
        final titleSpans = _buildHighlightedTextSpans(
          text: musicItem.title,
          query: query,
          isCurrentPlaying: isCurrentPlaying,
          isDisabled: musicItem.disabled,
        );

        return RichText(
          text: TextSpan(children: titleSpans),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        );
      },
    );
  }

  /// 构建副标题组件
  /// 显示艺术家和专辑信息，支持高亮显示
  Widget _buildSubtitleWidget(BuildContext context) {
    final subtitleText = '${musicItem.artist} - ${musicItem.album}';

    // 构建副标题的高亮文本
    final subtitleSpans = _buildHighlightedTextSpans(
      text: subtitleText,
      query: query,
      isCurrentPlaying: false,
      isDisabled: musicItem.disabled,
      isSubtitle: true,
    );

    return RichText(
      text: TextSpan(children: subtitleSpans),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 构建更多按钮
  Widget _buildMoreButton(BuildContext context) {
    return IconButton(
      onPressed: onMoreTap ?? () => _showMoreOptions(context),
      icon: Icon(
        Icons.more_vert,
        color: musicItem.disabled ? Colors.grey.shade400 : Colors.white,
        size: 20,
      ),
      constraints: const BoxConstraints(
        minWidth: 32,
        minHeight: 32,
      ),
      padding: EdgeInsets.zero,
    );
  }

  /// 构建高亮文本片段
  /// 支持搜索关键词高亮、当前播放状态和禁用状态
  List<TextSpan> _buildHighlightedTextSpans({
    required String text,
    required String query,
    required bool isCurrentPlaying,
    required bool isDisabled,
    bool isSubtitle = false,
  }) {
    // 如果没有搜索关键词，返回普通文本
    if (query.isEmpty) {
      return [
        TextSpan(
          text: text,
          style: _getTextStyle(
            isCurrentPlaying: isCurrentPlaying,
            isDisabled: isDisabled,
            isSubtitle: isSubtitle,
            isHighlight: false,
          ),
        ),
      ];
    }

    // 使用搜索ViewModel的高亮文本处理方法
    final searchViewModel = MusicSearchViewModel();

    // 如果文本包含HTML高亮标签，使用原有的解析方法
    if (text.contains('<span class="c_tx_highlight">')) {
      return searchViewModel.configHtmlDataAnalysis(
        htmlStr: text,
        normalColor: _getTextColor(
          isCurrentPlaying: isCurrentPlaying,
          isDisabled: isDisabled,
          isSubtitle: isSubtitle,
        ),
        primaryColor: isCurrentPlaying
            ? const Color.fromRGBO(50, 240, 140, 1)
            : const Color.fromRGBO(50, 240, 140, 1),
        disabled: isDisabled,
        fontSize: isSubtitle ? 12 : 14,
      );
    }

    // 手动高亮处理
    return _manualHighlight(
      text: text,
      query: query,
      isCurrentPlaying: isCurrentPlaying,
      isDisabled: isDisabled,
      isSubtitle: isSubtitle,
    );
  }

  /// 手动高亮处理
  List<TextSpan> _manualHighlight({
    required String text,
    required String query,
    required bool isCurrentPlaying,
    required bool isDisabled,
    required bool isSubtitle,
  }) {
    final List<TextSpan> spans = [];
    final lowerText = text.toLowerCase();
    final lowerQuery = query.toLowerCase();

    int start = 0;
    int index = lowerText.indexOf(lowerQuery);

    while (index != -1) {
      // 添加高亮前的普通文本
      if (index > start) {
        spans.add(TextSpan(
          text: text.substring(start, index),
          style: _getTextStyle(
            isCurrentPlaying: isCurrentPlaying,
            isDisabled: isDisabled,
            isSubtitle: isSubtitle,
            isHighlight: false,
          ),
        ));
      }

      // 添加高亮文本
      spans.add(TextSpan(
        text: text.substring(index, index + query.length),
        style: _getTextStyle(
          isCurrentPlaying: isCurrentPlaying,
          isDisabled: isDisabled,
          isSubtitle: isSubtitle,
          isHighlight: true,
        ),
      ));

      start = index + query.length;
      index = lowerText.indexOf(lowerQuery, start);
    }

    // 添加剩余的普通文本
    if (start < text.length) {
      spans.add(TextSpan(
        text: text.substring(start),
        style: _getTextStyle(
          isCurrentPlaying: isCurrentPlaying,
          isDisabled: isDisabled,
          isSubtitle: isSubtitle,
          isHighlight: false,
        ),
      ));
    }

    return spans.isEmpty
        ? [
            TextSpan(
              text: text,
              style: _getTextStyle(
                isCurrentPlaying: isCurrentPlaying,
                isDisabled: isDisabled,
                isSubtitle: isSubtitle,
                isHighlight: false,
              ),
            )
          ]
        : spans;
  }

  /// 获取文本样式
  TextStyle _getTextStyle({
    required bool isCurrentPlaying,
    required bool isDisabled,
    required bool isSubtitle,
    required bool isHighlight,
  }) {
    Color color = _getTextColor(
      isCurrentPlaying: isCurrentPlaying,
      isDisabled: isDisabled,
      isSubtitle: isSubtitle,
    );

    // 高亮文本使用特殊颜色
    if (isHighlight) {
      color = isCurrentPlaying
          ? const Color.fromRGBO(50, 240, 140, 1)
          : const Color.fromRGBO(50, 240, 140, 1);
    }

    return TextStyle(
      color: color,
      fontSize: isSubtitle ? 12 : 14,
      fontWeight: isHighlight ? FontWeight.w600 : FontWeight.w500,
    );
  }

  /// 获取文本颜色
  Color _getTextColor({
    required bool isCurrentPlaying,
    required bool isDisabled,
    required bool isSubtitle,
  }) {
    if (isDisabled) {
      return Colors.grey.shade400;
    }

    if (isCurrentPlaying) {
      return const Color.fromRGBO(50, 240, 140, 1);
    }

    if (isSubtitle) {
      return Colors.grey.shade300;
    }

    return Colors.white;
  }

  /// 显示更多选项
  void _showMoreOptions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.grey.shade900,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => _buildMoreOptionsSheet(context),
    );
  }

  /// 构建更多选项面板
  Widget _buildMoreOptionsSheet(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 歌曲信息
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              children: [
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade800,
                    borderRadius: BorderRadius.circular(8),
                    image: musicItem.albumArt != null
                        ? DecorationImage(
                            image: NetworkImage(musicItem.albumArt!),
                            fit: BoxFit.cover,
                          )
                        : null,
                  ),
                  child: musicItem.albumArt == null
                      ? const Icon(
                          Icons.music_note,
                          color: Colors.grey,
                          size: 24,
                        )
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        musicItem.title,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 2),
                      Text(
                        '${musicItem.artist} - ${musicItem.album}',
                        style: TextStyle(
                          color: Colors.grey.shade400,
                          fontSize: 12,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          const Divider(color: Colors.grey, height: 1),

          // 操作选项
          _buildOptionItem(
            icon: Icons.playlist_add,
            title: '添加到播放列表',
            onTap: () {
              Navigator.pop(context);
              _addToPlaylist(context);
            },
          ),
          _buildOptionItem(
            icon: Icons.favorite_border,
            title: '收藏',
            onTap: () {
              Navigator.pop(context);
              _addToFavorites(context);
            },
          ),
          _buildOptionItem(
            icon: Icons.share,
            title: '分享',
            onTap: () {
              Navigator.pop(context);
              _shareMusic(context);
            },
          ),
        ],
      ),
    );
  }

  /// 构建选项项
  Widget _buildOptionItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        child: Row(
          children: [
            Icon(icon, color: Colors.white, size: 20),
            const SizedBox(width: 16),
            Text(
              title,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 添加到播放列表
  void _addToPlaylist(BuildContext context) {
    final playerViewModel = context.read<MusicPlayerViewModel>();
    playerViewModel.addToPlaylist(musicItem);

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('已添加到播放列表'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 添加到收藏
  void _addToFavorites(BuildContext context) {
    // TODO: 实现收藏功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('收藏功能待实现'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 分享音乐
  void _shareMusic(BuildContext context) {
    // TODO: 实现分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('分享功能待实现'),
        duration: Duration(seconds: 2),
      ),
    );
  }
}
